import { defineStore } from 'pinia'
import router from '@/router'
import { loginAPI, getUserInfoAPI } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: localStorage.getItem('mock-token') || '',
    lastActiveTime: null
  }),
  actions: {
    async login(credentials) {
      try {
        const { data } = await loginAPI(credentials)
        
        // 存储token
        this.token = data.token
        localStorage.setItem('mock-token', data.token)
        
        // 存储用户信息
        this.userInfo = data.userInfo
        localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
        
        this.lastActiveTime = Date.now()
        return true
      } catch (error) {
        this.logout()
        throw error
      }
    },
    
    async getUserInfo() {
      if (!this.token) return
      const { data } = await getUserInfoAPI()
      this.userInfo = data
    },
    
    logout() {
      this.token = ''
      this.userInfo = null
      localStorage.removeItem('mock-token')
      localStorage.removeItem('userInfo')
      router.push('/login')
    },
    updateActiveTime() {
      this.lastActiveTime = Date.now()
    }
  },
  getters: {
    isLoggedIn: (state) => !!state.token,
    permissions: (state) => state.userInfo?.permissions || state.userInfo?.roles || []
  }
})